package com.xueshandai.db.migration.database.implement;

import com.xueshandai.db.migration.database.DataBase;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Zetas on 2014/12/12.
 */
public class DataBaseMySQLImpl implements DataBase {

    private String address;
    private int port;
    private String username;
    private String password;
    private String databaseName;

    public DataBaseMySQLImpl(String address, int port, String username, String password, String databaseName) {
        this.address = address;
        this.port = port;
        this.username = username;
        this.password = password;
        this.databaseName = databaseName;
    }

    public Connection getConnection() {

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            logger.error(e);
        }

        String url = "jdbc:mysql://"+address+":"+port+"/"+databaseName;

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            logger.error(e);
        }

        logger.info("数据库连接获取成功：" + connection);
        return connection;

    }

    @Override
    public List<String> getAllTables() {
        List<String> tableList = new LinkedList<String>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = this.getConnection();
            preparedStatement = connection.prepareStatement("select table_name as Name from information_schema.tables where table_schema='xueshandai'");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                tableList.add(resultSet.getString("Name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if ( resultSet != null ) try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if ( preparedStatement != null ) try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if ( connection != null ) try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return tableList;
    }


}
